<template>
    <el-form
        :inline="true"
        ref="searchFormRef"
        style="max-width: 100%"
        label-width="auto"
        :model="queryConditions"
        class="demo-ruleForm"
        status-icon
    >
        <el-form-item label="供应商编码" prop="code">
            <el-input
                v-model="queryConditions.code"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-form-item label="供应商名称" prop="name">
            <el-input
                v-model="queryConditions.name"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-form-item label="供应商手机号" prop="phone">
            <el-input
                v-model="queryConditions.phone"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-button type="primary" :icon="Search" @click="search">查询</el-button>
        <el-button type="primary" :icon="RefreshRight" @click="resetForm">重置</el-button>
    </el-form>
    <!-- 隐藏的文件输入框，用于导入 -->
    <input
        type="file"
        ref="fileInput"
        style="display: none"
        accept=".xlsx,.xls"
        @change="handleFileSelect"
    />
    <TestPage
        :table-data="indexTableData"
        :columns="tableColumns"
        :current-page="pageNo"
        :total="allPage"
        :page-size="pageSize"
        @page-change="handlePageChange"
        @action="handleTableAction"
        @edit="handleEditAction"
        @delete="handleDeleteAction"
    />

    <!-- 弹窗显示 AddProvider -->
    <el-dialog
        title="新增供应商"
        v-model="showAddDialog"
        width="40%"
        :before-close="handleDialogClose"
    >
        <AddProvider
            @submit-success="handleAddSuccess"
            @cancel="handleDialogClose"
        />
    </el-dialog>
    <!-- 编辑供应商弹窗 -->
    <el-dialog
        title="编辑供应商"
        v-model="showEditDialog"
        width="40%"
        :before-close="handleDialogClose"
    >
        <AddProvider
            :provider="editingProvider"
            @submit-success="handleEditSuccess"
            @cancel="handleDialogClose"
        />
    </el-dialog>
</template>

<script setup lang="ts">
import TestPage from "@/test/TestPage.vue";
import AddProvider from "@/basic-view/provider/AddProvider.vue";
import {Search, RefreshRight} from '@element-plus/icons-vue';
import {ref, reactive, nextTick, computed} from 'vue';
import {ElMessageBox, ElMessage, type FormInstance, ElLoading} from 'element-plus';
import type {PublicProvider} from "@/types/public-cg/provider.ts";
import request from "@/util/request.ts";

let pageNo = ref(1);
let pageSize = ref(3);
let allPage = ref(0);

// 查询条件
const queryConditions = reactive({
    code: '',
    name: '',
    phone: ''
});

const tableColumns = ref([
    {prop: 'index', label: '序号'},
    {prop: 'code', label: '供应商编码'},
    {prop: 'name', label: '供应商名称'},
    {prop: 'area', label: '供应商业务地区'},
    {prop: 'address', label: '供应商地址'},
    {prop: 'phone', label: '手机号'},
    {prop: 'transactions', label: '交易'},
]);

let tableData = ref<PublicProvider[]>([]);


//计算序号
const indexTableData = computed(() => {
    return tableData.value.map((item, index) => ({
        ...item,
        index: (pageNo.value - 1) * pageSize.value + index + 1
    }))
})

const showAddDialog = ref(false); // 新增弹窗
const showEditDialog = ref(false); // 编辑弹窗
const editingProvider = ref<PublicProvider | null>(null); // 当前编辑的供应商
const fileInput = ref<HTMLInputElement | null>(null); // 文件输入框引用

const handlePageChange = (newPage: number) => {
    pageNo.value = newPage;
    fetchData(newPage);
};

const handleTableAction = (actionName: string) => {
    if (actionName === 'add') {
        showAddDialog.value = true; // 打开新增弹窗
    }
    if (actionName === 'import') {
        fileInput.value?.click(); // 触发文件选择
    }
    if (actionName === 'export') {
        handleExport(); // 触发导出
    }
    if (actionName === 'downLoadTemplate') {
        handleDownloadTemplate();
    }
};

// 导出供应商数据
const handleExport = async () => {
    const params = {
        pageNo: pageNo.value,
        pageSize: pageSize.value,
        code: queryConditions.code,
        name: queryConditions.name,
        phone: queryConditions.phone,
    };
    const loading = ElLoading.service({text: "正在导出..."});
    try {
        const response = await request.post("/basic/Provider/export", params, {
            responseType: "blob",
        });
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "供应商信息表.xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success("导出成功");
    } catch (error) {
        console.error("导出失败:", error);
        ElMessage.error("导出失败，请稍后重试");
    } finally {
        loading.close();
    }
};

//下载模板
const handleDownloadTemplate = async () => {
    try {
        const response = await request.get('/basic/Provider/template', {
            responseType: 'blob',
        });
        console.log(response)
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '供应商信息表.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success('模板下载成功');
    } catch (error) {
        ElMessage.error('模板下载失败，请稍后重试');
    }
}

// 导入
const handleFileSelect = async (event: Event) => {
    const input = event.target as HTMLInputElement;
    const file = input.files?.[0];
    if (!file) {
        ElMessage.warning('未选择文件');
        return;
    }

    // 校验文件后缀
    const allowedExtensions = ['.xlsx', '.xls'];
    const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
    if (!allowedExtensions.includes(fileExtension)) {
        ElMessage.error('文件格式不正确，仅支持 .xlsx 和 .xls 文件');
        input.value = ''; // 重置文件输入框
        return;
    }

    // 校验文件大小
    const maxFileSize = 10 * 1024 * 1024; //10MB
    if (file.size > maxFileSize) {
        ElMessage.error(`文件大小超过限制，最大允许10MB，当前文件大小'${file.size.toFixed(2)}MB'`);
        input.value = ''; //重置
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    const loading = ElLoading.service({text: '正在导入...'});
    try {
        const response = await request.post('/basic/Provider/import', formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        });
        console.log(response.data.msg, ",", response.data.code)
        if (response.data.code === '200') {
            ElMessage.success('导入成功');
            await fetchData(pageNo.value); // 刷新表格数据
        } else {
            ElMessage.error(response.data.msg || "导入失败！");
        }
    } catch (error) {
        ElMessage.error('导入失败，请稍后重试');
        console.log(error)
    } finally {
        loading.close();
        input.value = ''; // 重置文件输入框
    }
};


// 修改弹窗
const handleEditAction = (provider: PublicProvider) => {
    editingProvider.value = {...provider}; // 复制供应商数据
    showEditDialog.value = true; // 打开修改弹窗
};

const handleDeleteAction = async (provider: PublicProvider) => {
    try {
        await ElMessageBox.confirm('确定删除此供应商？此操作不可恢复。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        await request.post(`/basic/Provider/deleteProvider?id=${provider.id}`);
        ElMessage.success('删除成功');
        await fetchData(pageNo.value); // 刷新
    } catch (error) {
        ElMessage.error('删除失败，请稍后重试');
        console.error('删除失败:', error);
    }
};

const handleAddSuccess = () => {
    showAddDialog.value = false;
    fetchData(pageNo.value); // 刷新
};

const handleEditSuccess = () => {
    showEditDialog.value = false;
    editingProvider.value = null;
    fetchData(pageNo.value); // 刷新表格
};

const handleDialogClose = () => {
    ElMessageBox.confirm('确定关闭新增供应商窗口？未保存的数据将丢失。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        showAddDialog.value = false; // 确认关闭
        showEditDialog.value = false;
    });
};

const searchFormRef = ref<FormInstance>();

// 查询
const search = () => {
    pageNo.value = 1; // 重置到第一页
    fetchData(1);
};

// 重置表单
const resetForm = () => {
    if (!searchFormRef.value) return;
    nextTick(() => {
        searchFormRef.value!.resetFields();
        pageNo.value = 1;
        fetchData(1);
    });
};


async function fetchData(page: number) {
    try {
        let response = await request.post('/basic/Provider/selectProviderByPage', {
            pageNo: page,
            pageSize: pageSize.value,
            code: queryConditions.code,
            name: queryConditions.name,
            phone: queryConditions.phone
        });
        tableData.value = response.data.data.list;
        allPage.value = response.data.data.total;
    } catch (error) {
        ElMessage.error('获取供应商数据失败');
        tableData.value = [];
        allPage.value = 0;
        console.error('获取数据失败:', error);
    }
}

fetchData(1);
</script>

<style scoped>
</style>
```
